package team.you.change.service.serviceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import team.you.change.dao.NoticeMapper;
import team.you.change.pojo.Notice;
import team.you.change.util.Result;
import team.you.change.service.NoticeService;
import team.you.change.util.YuoUtil;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class NoticeServiceImpl implements NoticeService {
    @Autowired
    private NoticeMapper noticeMapper;
    @Override
    public Result getAllNotices(Integer page, Integer limit) {
        Result result = new Result();
        List<Notice> notices = noticeMapper.selectAll(YuoUtil.getPage(page, limit), limit);
        Integer count = noticeMapper.getCount();
        return YuoUtil.setData(result, notices, count);
    }

    @Override
    public Result del(String id) {
        Result result = new Result();
        Notice notice = noticeMapper.selectByPrimaryKey(id);
        if (notice != null) {
            try {
                return YuoUtil.crudMsg(noticeMapper.deleteByPrimaryKey(id), result);
            }catch (Exception e){
                return YuoUtil.setErrorMsg(e, result);
            }
        } else {
            result.setCode(500);
            result.setMsg("该行不存在");
        }
        return result;
    }

    @Override
    @Transactional
    public Result delete(String[] ids) {
        Result result = new Result();
        try {
            for (int i = 0; i < ids.length; i++) {
                noticeMapper.deleteByPrimaryKey(ids[i]);
            }
            return result;
        } catch (Exception e) {
            return YuoUtil.setErrorMsg(e, result);
        }
    }

    @Override
    public Result update(String id, String value, String field) {
        Result result = new Result();
        try {
            return YuoUtil.crudMsg(noticeMapper.UpdateByKey(id, value, field), result);
        } catch (Exception e) {
            return YuoUtil.setErrorMsg(e, result);
        }
    }

    @Override
    public Result add(Notice notice) {
        Result result = new Result();
        String uuid = UUID.randomUUID().toString();
        notice.setId(uuid);
        notice.setTime(new Date());
        try {
            return YuoUtil.crudMsg(noticeMapper.insert(notice), result);
        }catch (Exception e){
            return YuoUtil.setErrorMsg(e, result);
        }
    }

    @Override
    public Result getTop() {
        Result result = new Result();
        List<Notice> notices = noticeMapper.getTop();
        result.setData(notices);
        return result;
    }

    @Override
    public Result getPage() {
        Result result = new Result();
        Integer count = noticeMapper.getCount();
        Double v = Math.ceil(count / 4.0) - 1;
        result.setCount(v.intValue());
        return result;
    }
}
